<template>
  <div>{{ formattedValue }}</div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue';

const props = defineProps({
  endValue: {
    type: Number,
    required: true
  },
  duration: {
    type: Number,
    default: 2000
  },
  // 千分位格式化启用参数，默认启用
  enableThousandSeparator: {
    type: Boolean,
    default: true
  }
});

const value = ref(0);

// 千分位格式化函数
const formatNumberWithCommas = (number) => {
  return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

const formattedValue = computed(() => {
  const rawValue = Math.floor(value.value);
  return props.enableThousandSeparator ? formatNumberWithCommas(rawValue) : rawValue.toString();
});

const animateNumber = () => {
  const startTime = performance.now();
  const startValue = value.value;
  const endValue = props.endValue;
  const duration = props.duration;

  const step = (timestamp) => {
    const elapsed = timestamp - startTime;
    if (elapsed < duration) {
      value.value = startValue + (endValue - startValue) * (elapsed / duration);
      requestAnimationFrame(step);
    } else {
      value.value = endValue;
    }
  };

  requestAnimationFrame(step);
};

onMounted(() => {
  animateNumber();
});

watch(() => props.endValue, () => {
  animateNumber();
});
</script>